/*
* Copyright (c) 2017 Zhangyujie (Tocy)

* This file is part of PlayerDemo project.
*/

#include "RenderYuv.h"
#include <cstdio>
#include <unistd.h>
#include <signal.h>


bool yuv_read(const char * fn, int read_size, unsigned char * data)
{
    static FILE * file = fopen(fn, "rb");
    if (NULL != file) {
        size_t rc = fread(data, 1, read_size, file);
        printf("%s %d read_size  %u", __FUNCTION__, __LINE__, (unsigned int)rc);
#if 0
        if (rc > 0)
        {
            static FILE * fout = fopen("test_cif.yuv", "wb");
            if (fout) {
                fwrite(data, 1, rc, fout);
                fflush(fout);
            }
        }
#endif
        return rc > 0;
    }
    else
    {
        printf("file %s cannot open\n", fn);
    }

    return false;
}

void signal_handle(int sig)
{
    printf("recv signal %d\n", sig);
    exit(0);
}

int main(int argc, char * argv[])
{
    signal(SIGINT , signal_handle); /* Interrupt (ANSI).    */
    signal(SIGTERM, signal_handle); /* Termination (ANSI).  */

    SDL_Init(SDL_INIT_EVERYTHING);

    // read yuv and render this
    const int WIDTH = 352;
    const int HEIGHT = 288;
    int plane_size = WIDTH * HEIGHT;
    unsigned char  * data_buf = new unsigned char [int(plane_size * 1.5)];

    YuvRenderer render;
    SDL_Rect rect;
    rect.x = rect.y = 200;
    rect.w = WIDTH;
    rect.h = HEIGHT;
    if (!render.Init(rect))
    {
        printf("init render failed\n");
        return -2;
    }
    int stride[3] = {WIDTH, WIDTH>>1, WIDTH>>1};
    unsigned char * data[3] = {data_buf, data_buf + plane_size, data_buf + plane_size + (plane_size>>2)};

    int frame = 0;
    int read_size = plane_size * 3  / 2;
    for (;;)
    {
        ++frame;   
        if (!yuv_read(argv[1], read_size, data_buf)) {
            printf("yuv_read failed");
            break;
        }
        printf("after yuv_read %d\n", frame);
        render.Update(WIDTH, HEIGHT, data, stride);
        printf("after render.Update\n");
        render.Render();
        printf("after render.Render\n");

        // add this for bug fix: after a while playing, the window become gray. not colorful.
        SDL_PumpEvents();
        SDL_PumpEvents();
        SDL_PumpEvents();
        sleep(1);
    }

    render.Uninit();

    if (NULL != data_buf)
    {
        delete [] data_buf;
        data_buf = NULL;
    }


    SDL_Quit();

    printf("program end\n");
    return 0;
}